import { toPay } from "@/api/order";
import { OrderPayStateEnum, PayChannelCodeEnum } from "@/enums/orderEnum";
import { Toast } from "@/utils";
import { isJSON } from "@/utils/is";
import { logManager } from "@/utils/log";
import { useUserStoreWithOut } from '@/store/modules/user';
import dayjs from "dayjs";
import durationPlugin from 'dayjs/plugin/duration';
import type { Ref } from "vue";
dayjs.extend(durationPlugin)

/**
 * @description 微信支付Api
 * @date 23/02/2023
 * @export
 * @param {string} payCode
 */
export async function requestPayment(payCode: string, isOpenOfficialAccount: boolean = true) {
  if (!payCode) {
    Toast('payCode 不能为空')
    return Promise.reject('payCode 不能为空')
  }
  const useUser = useUserStoreWithOut();
  uni.showLoading({ title: '支付中...', mask: true })
  const { prePayTn } = await toPay({ paymentOrderNum: payCode, payChannelCode: PayChannelCodeEnum.WECHAT, terminal: 'APPLET' })
  if (!prePayTn || !isJSON(prePayTn)) {
    logManager.error(prePayTn)
    uni.hideLoading()
    Toast('支付参数错误')
    return Promise.reject('支付参数错误')
  }
  let op: UniApp.RequestPaymentOptions = isJSON(prePayTn)
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: '',
      timeStamp: op.timeStamp,
      nonceStr: op.nonceStr,
      package: op.package,
      signType: op.signType,
      paySign: op.paySign,
      success: (res) => {
        let timer = setTimeout(() => {
          resolve(res)
          clearTimeout(timer)
        }, 3000)
        uni.showModal({
          title: '提示',
          content: '支付成功',
          showCancel: false,
          success: () => {
            clearTimeout(timer)
            isOpenOfficialAccount && (useUser.openOfficialAccount = true) // 弹出关注公众号
            resolve(res)
          }
        })
      },
      fail: (err) => {
        logManager.error(prePayTn, err)
        reject(err)
      },
      complete: () => uni.hideLoading()
    })
  });

}

/**
 * @description 倒计时函数
 * @date 10/11/2023
 * @export
 * @param {number} ms 总时长
 * @param {Ref<string>} countdownTimeRef 每次变化的时间(分:秒)
 */
export function countdown_timer(ms: number, countdownTimeRef: Ref<string>, format?: 'mm:ss', callback?: () => void) {
  let countdownInterval: string | number | NodeJS.Timeout | undefined
  let countdownTime = ms
  function stop() {
    clearInterval(countdownInterval);
  }
  countdownInterval = setInterval(() => {
    countdownTime--;
    const duration = dayjs.duration(countdownTime, 'seconds');
    const dateObj: { [x: string]: number | string } = {
      d: duration.days(),
      h: duration.hours(),
      m: duration.minutes(),
      s: duration.seconds()
    }
    Object.keys(dateObj).forEach(v => {
      dateObj[v] = dateObj[v] as number < 10 ? `0${dateObj[v]}` : dateObj[v]
    })

    if (format === 'mm:ss') {
      countdownTimeRef.value = `${dateObj.m}:${dateObj.s}`
    } else {
      let str = `${dateObj.h}:${dateObj.m}:${dateObj.s}`
      if (dateObj.d && dateObj.d !== '00') {
        str = `${dateObj.d}天 ${str}`
      }
      countdownTimeRef.value = str
    }

    // 倒计时结束时触发的事件
    if (countdownTime < 0) {
      clearInterval(countdownInterval);
      callback?.()
      console.log('倒计时结束！');
    }
  }, 1000);
  return stop
}